﻿namespace GoodAdmin.System;

/// <summary>
/// 系统作业任务服务
/// </summary>
public class SysJobService : ISysJobService, ITransient
{   
    private readonly ISchedulerFactory _schedulerFactory;
    private readonly DynamicJobCompiler _dynamicJobCompiler;
    private DbRepository<SysJobDetail> SysJobDetailRep => new();
    private DbRepository<SysJobTrigger> SysJobTriggerRep => new();
    private DbRepository<SysJobTriggerRecord> SysJobTriggerRecordRep => new();
    public SysJobService(
        ISchedulerFactory schedulerFactory,
        DynamicJobCompiler dynamicJobCompiler)
    {
        _schedulerFactory = schedulerFactory;
        _dynamicJobCompiler = dynamicJobCompiler;
    }

    /// <summary>
    /// 获取作业分页列表
    /// </summary>
    public async Task<SqlSugarPagedList<JobDetailOutput>> PageJobDetail(JobDetailPageInput input)
    {
        var jobDetails = await SysJobDetailRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.JobId), u => u.JobId.Contains(input.JobId))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Description), u => u.Description.Contains(input.Description))
            .Select(d => new JobDetailOutput
            {
                JobDetail = d,
            }).ToPagedListAsync(input.PageIndex, input.PageSize);

        await SysJobDetailRep.AsSugarClient().ThenMapperAsync(jobDetails.Items, async u =>
        {
            u.JobTriggers = await SysJobTriggerRep.GetListAsync(t => t.JobId == u.JobDetail.JobId);
        });

        // 提取中括号里面的参数值
        var rgx = new Regex(@"(?i)(?<=\[)(.*)(?=\])");
        foreach (var job in jobDetails.Items)
        {
            foreach (var jobTrigger in job.JobTriggers)
            {
                jobTrigger.Args = rgx.Match(jobTrigger.Args ?? "").Value;
            }
        }
        return jobDetails;
    }

    /// <summary>
    /// 添加作业
    /// </summary>
    /// <returns></returns>
    public async Task AddJobDetail(JobDetailInput input)
    {
        var isExist = await SysJobDetailRep.IsAnyAsync(u => u.JobId == input.JobId && u.Id != input.Id);
        if (isExist)
            throw Oops.Oh(JobErrorCode.J001);

        // 动态创建作业
        Type jobType;
        switch (input.CreateType)
        {
            case JobConst.JobCreateType_Script when string.IsNullOrEmpty(input.ScriptCode):
                throw Oops.Oh(JobErrorCode.J005);
            case JobConst.JobCreateType_Script:
                {
                    jobType = _dynamicJobCompiler.BuildJob(input.ScriptCode);

                    if (jobType.GetCustomAttributes(typeof(JobDetailAttribute)).FirstOrDefault() is not JobDetailAttribute jobDetailAttribute)
                        throw Oops.Oh(JobErrorCode.J006);
                    if (jobDetailAttribute.JobId != input.JobId)
                        throw Oops.Oh(JobErrorCode.J004);
                    break;
                }
            case JobConst.JobCreateType_Http:
                jobType = typeof(HttpJob);
                break;

            default:
                throw new NotSupportedException();
        }

        _schedulerFactory.AddJob(
            JobBuilder.Create(jobType)
                .LoadFrom(input.Adapt<SysJobDetail>()).SetJobType(jobType));

        // 延迟一下等待持久化写入，再执行其他字段的更新
        await Task.Delay(500);
        await SysJobDetailRep.AsUpdateable()
            .SetColumns(u => new SysJobDetail { CreateType = input.CreateType, ScriptCode = input.ScriptCode })
            .Where(u => u.JobId == input.JobId).ExecuteCommandAsync();
    }

    /// <summary>
    /// 更新作业
    /// </summary>
    /// <returns></returns>
    public async Task UpdateJobDetail(JobDetailInput input)
    {
        var isExist = await SysJobDetailRep.IsAnyAsync(u => u.JobId == input.JobId && u.Id != input.Id);
        if (isExist)
            throw Oops.Oh(JobErrorCode.J001);

        var sysJobDetail = await SysJobDetailRep.GetFirstAsync(u => u.Id == input.Id);
        if (sysJobDetail.JobId != input.JobId)
            throw Oops.Oh(JobErrorCode.J002);

        var scheduler = _schedulerFactory.GetJob(sysJobDetail.JobId);
        var oldScriptCode = sysJobDetail.ScriptCode; // 旧脚本代码
        input.Adapt(sysJobDetail);

        if (input.CreateType == JobConst.JobCreateType_Script)
        {
            if (string.IsNullOrEmpty(input.ScriptCode))
                throw Oops.Oh(JobErrorCode.J005);

            if (input.ScriptCode != oldScriptCode)
            {
                // 动态创建作业
                var jobType = _dynamicJobCompiler.BuildJob(input.ScriptCode);

                if (jobType.GetCustomAttributes(typeof(JobDetailAttribute)).FirstOrDefault() is not JobDetailAttribute jobDetailAttribute)
                    throw Oops.Oh(JobErrorCode.J006);
                if (jobDetailAttribute.JobId != input.JobId)
                    throw Oops.Oh(JobErrorCode.J004);

                scheduler?.UpdateDetail(JobBuilder.Create(jobType).LoadFrom(sysJobDetail).SetJobType(jobType));
            }
        }
        else
        {
            scheduler?.UpdateDetail(scheduler.GetJobBuilder().LoadFrom(sysJobDetail));
        }

        // Tip: 假如这次更新有变更了 JobId，变更 JobId 后触发的持久化更新执行，会由于找不到 JobId 而更新不到数据
        // 延迟一下等待持久化写入，再执行其他字段的更新
        await Task.Delay(500);
        await SysJobDetailRep.UpdateAsync(sysJobDetail);
    }

    /// <summary>
    /// 删除作业
    /// </summary>
    /// <returns></returns>
    public async Task DeleteJobDetail(JobDetailIdInput input)
    {
        _schedulerFactory.RemoveJob(input.JobId);

        // 如果 _schedulerFactory 中不存在 JodId，则无法触发持久化，下面的代码确保作业和触发器能被删除
        await SysJobDetailRep.DeleteAsync(u => u.JobId == input.JobId);
        await SysJobTriggerRep.DeleteAsync(u => u.JobId == input.JobId);
    }

    /// <summary>
    /// 获取触发器列表
    /// </summary>
    public async Task<List<SysJobTrigger>> GetJobTriggerList([FromQuery] JobDetailIdInput input)
    {
        return await SysJobTriggerRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.JobId), u => u.JobId.Contains(input.JobId))
            .ToListAsync();
    }

    /// <summary>
    /// 添加触发器
    /// </summary>
    /// <returns></returns>
    public async Task AddJobTrigger(JobTriggerInput input)
    {
        var isExist = await SysJobTriggerRep.IsAnyAsync(u => u.TriggerId == input.TriggerId && u.Id != input.Id);
        if (isExist)
            throw Oops.Oh(JobErrorCode.J001);

        var jobTrigger = input.Adapt<SysJobTrigger>();
        jobTrigger.Args = "[" + jobTrigger.Args + "]";

        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.AddTrigger(Triggers.Create(input.AssemblyName, input.TriggerType).LoadFrom(jobTrigger));
    }

    /// <summary>
    /// 更新触发器
    /// </summary>
    /// <returns></returns>
    public async Task UpdateJobTrigger(JobTriggerInput input)
    {
        var isExist = await SysJobTriggerRep.IsAnyAsync(u => u.TriggerId == input.TriggerId && u.Id != input.Id);
        if (isExist)
            throw Oops.Oh(JobErrorCode.J001);

        var jobTrigger = input.Adapt<SysJobTrigger>();
        jobTrigger.Args = "[" + jobTrigger.Args + "]";

        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.UpdateTrigger(Triggers.Create(input.AssemblyName, input.TriggerType).LoadFrom(jobTrigger));
    }

    /// <summary>
    /// 删除触发器
    /// </summary>
    /// <returns></returns>
    public async Task DeleteJobTrigger(JobTriggerIdInput input)
    {
        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.RemoveTrigger(input.TriggerId);

        // 如果 _schedulerFactory 中不存在 JodId，则无法触发持久化，下行代码确保触发器能被删除
        await SysJobTriggerRep.DeleteAsync(u => u.JobId == input.JobId && u.TriggerId == input.TriggerId);
    }

    /// <summary>
    /// 暂停所有作业
    /// </summary>
    /// <returns></returns>
    public void PauseAllJob()
    {
        _schedulerFactory.PauseAll();
    }

    /// <summary>
    /// 启动所有作业
    /// </summary>
    /// <returns></returns>
    public void StartAllJob()
    {
        _schedulerFactory.StartAll();
    }

    /// <summary>
    /// 暂停作业
    /// </summary>
    public void PauseJob(JobDetailIdInput input)
    {
        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.Pause();
    }

    /// <summary>
    /// 启动作业
    /// </summary>
    public void StartJob(JobDetailIdInput input)
    {
        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.Start();
    }

    /// <summary>
    /// 取消作业
    /// </summary>
    public void CancelJob(JobDetailIdInput input)
    {
        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.Cancel();
    }

    /// <summary>
    /// 执行作业
    /// </summary>
    /// <param name="input"></param>
    public void RunJob(JobDetailIdInput input)
    {
        if (_schedulerFactory.TryRunJob(input.JobId,out _) != ScheduleResult.Succeed)
            throw Oops.Oh(JobErrorCode.J003);
    }

    /// <summary>
    /// 暂停触发器
    /// </summary>
    public void PauseTrigger(JobTriggerIdInput input)
    {
        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.PauseTrigger(input.TriggerId);
    }

    /// <summary>
    /// 启动触发器
    /// </summary>
    public void StartTrigger(JobTriggerIdInput input)
    {
        var scheduler = _schedulerFactory.GetJob(input.JobId);
        scheduler?.StartTrigger(input.TriggerId);
    }

    /// <summary>
    /// 强制唤醒作业调度器
    /// </summary>
    public void CancelSleep()
    {
        _schedulerFactory.CancelSleep();
    }

    /// <summary>
    /// 强制触发所有作业持久化
    /// </summary>
    public void PersistAll()
    {
        _schedulerFactory.PersistAll();
    }


    /// <summary>
    /// 获取作业触发器运行记录分页列表
    /// </summary>
    public async Task<SqlSugarPagedList<SysJobTriggerRecord>> PageJobTriggerRecord(JobTriggerRecordPageInput input)
    {
        return await SysJobTriggerRecordRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.JobId), u => u.JobId==input.JobId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.TriggerId), u => u.TriggerId==input.TriggerId)
            .ToPagedListAsync(input.PageIndex, input.PageSize);
    }
}